package com.amkai.aes.webservice.binary.objecthandler.casehistory;

import java.io.Serializable;
import java.util.List;

import org.hibernate.Query;

import com.amkai.aes.aescommon.service.binary.job.casehistory.SerialNumberJob;
import com.amkai.aes.aescommon.service.result.casehistory.SerialNumberJobResult;
import com.amkai.aes.generatedbeans.inventory.SerialNumber;
import com.amkai.aes.webservice.binary.JobObjectHandler;
import com.amkai.common.extensions.hibernate.config.SiteManager;
import com.amkai.common.extensions.hibernate.config.manager.SessionManager;

public class SerialNumberJobHandler implements JobObjectHandler<SerialNumberJob, Serializable, SerialNumberJobResult> {

	private static final String SERIAL_NUMBER_BY_ROOM = "From SerialNumber sn where sn.stock.inventoryElement.supplyResourceItem.id = :sriId and sn.room.id = :roomId and sn.stock.quantityOnHand > 0";
	
	@Override
	public SerialNumberJobResult process(SerialNumberJob job, Serializable object) throws Exception {
		SerialNumberJobResult result = new SerialNumberJobResult();
		result.setSerialNumber(null);
		SessionManager sm = null;

		if (job != null && job.getRoom() != null && job.getSupplyResourceItem() != null) {

			try {
				sm = SiteManager.Start();
				Query query = sm.execute(SERIAL_NUMBER_BY_ROOM);
				query.setParameter("sriId", job.getSupplyResourceItem().getId());
				query.setParameter("roomId", job.getRoom().getId());
				
				List<SerialNumber> serialNumbers = query.list();
				if (serialNumbers != null && serialNumbers.size() > 0) {
					SerialNumber sn = serialNumbers.get(0);
					sn.getId();
					sn.getSerial();
					result.setSerialNumber(sn);
					
				}
			} finally {
				sm.closeSession();
			}
		}

		return result;
	}

}
